<#assign title="资源管理-用户"/>
<#include "/layout/layout.html"/>
<#macro link>
</#macro>

<#macro content>
    <div class="container-fluid" style="margin-top: 10px">
        <div class="row">
            <div class="col-md-12">
                <div id="toolbar">
                    <a href="javascript:void(0);" class="btn btn-primary" id="addUser" ><span class="glyphicon glyphicon-plus"></span>新增</a>
                    <a href="javascript:void(0);" class="btn btn-default" id="deleteUsers"><span class="glyphicon glyphicon-minus"></span>删除</a>
                </div>
                <table id="userTable"></table>
            </div>
        </div>
    </div>

    <div id="addModel" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">新增用户</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-2"><label for="addUserName"><span class="hd-span">用户帐号</span></label></div>
                        <div class="col-md-10"><input type="text" id="addUserName" class="hd-input-form form-control" ></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="addRealName"><span class="hd-span">真实姓名</span></label></div>
                        <div class="col-md-10"><input type="text" id="addRealName" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="addEmail"><span class="hd-span">邮箱</span></label></div>
                        <div class="col-md-10"><input type="text" id="addEmail" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><span class="hd-span">角色</span></div>
                        <div class="col-md-10" style="height: 270px;overflow: auto;margin-top: 5px">
                            <ul id="addRoles" class="ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" id="addUserDo" class="btn btn-primary">确认</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
    <div id="editModel" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">修改用户</h4>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-2"><label for="editUserName"><span class="hd-span">用户帐号</span></label></div>
                        <div class="col-md-10"><input type="text" id="editUserName" readonly class="hd-input-form form-control" ></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="editRealName"><span class="hd-span">真实姓名</span></label></div>
                        <div class="col-md-10"><input type="text" id="editRealName" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><label for="editEmail"><span class="hd-span">邮箱</span></label></div>
                        <div class="col-md-10"><input type="text" id="editEmail" class="hd-input-form form-control"></div>
                    </div>
                    <div class="row" style="margin-top: 10px;">
                        <div class="col-md-2"><span class="hd-span">角色</span></div>
                        <div class="col-md-10" style="height: 270px;overflow: auto;margin-top: 5px">
                            <ul id="editRoles" class="ztree"></ul>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                    <button type="button" id="editUserDo" class="btn btn-primary">确认</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal-dialog -->
    </div>
</#macro>

<#macro script>
    <script type="text/javascript">
        $(function () {
            const addTreeId = "addRoles";
            const editTreeId="editRoles";
            const setting = {
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pId",
                        rootPId: 0
                    }
                }, check: {
                    enable: true,
                    chkStyle: "checkbox",
                    chkboxType: {"Y": "ps", "N": "ps"}
                }
            };
            //获取自定义所有用户
            const $userTable = $("#userTable").bootstrapTable({
                url: rootPath + "/user/custom/all",         //请求后台的URL（*）
                method: 'get',                      //请求方式（*）
                height: 460,
                showRefresh: true,
                showColumns: true,
                search: true,
                toolbar: '#toolbar',                //工具按钮用哪个容器
                striped: true,                      //是否显示行间隔色
                cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,                   //是否显示分页（*）
                sortable: true,                     //是否启用排序
                sortOrder: "asc",                   //排序方式
                sidePagination: "client",           //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,                       //初始化加载第一页，默认第一页
                pageSize: 10,                       //每页的记录行数（*）
                pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
                strictSearch: true,
                clickToSelect: true,                //是否启用点击选中行
                uniqueId: "id",                     //每一行的唯一标识，一般为主键列
                cardView: false,                    //是否显示详细视图
                detailView: false,                   //是否显示父子表
                columns: [{
                    checkbox: true,
                }, {
                    field: 'username',
                    sortable: true,
                    title: '帐号'
                }, {
                    field: 'realname',
                    sortable: true,
                    title: '姓名'
                }, {
                    field: 'email',
                    sortable: true,
                    title: '邮箱'
                }, {
                    title: '操作',
                    clickToSelect: false,
                    formatter: function (v, r,i) {
                        return "<button name='edit' data-username='"+r.username+"' data-realname='"+r.realname+"' data-email='"+r.email+"' class='btn btn-default btn-xs'>修改</button>" +
                            "<button name='delete' data-username='" +r.username + "' class='btn btn-default btn-xs'>删除</button>"+
                                "<button data-username='"+r.username+"' class='btn btn-default btn-xs' name='resetPass'>密码重置</button>"
                    }
                }]
            });
            //自定义用户中的编辑按钮事件
            $("#userTable").on("click","button[name='edit']",function (e) {
                let username=$(this).data("username");
                $('#editUserName').val(username);
                $('#editRealName').val($(this).data("realname"));
                $("#editEmail").val($(this).data("email"));
                loadRole(username,editTreeId);
                $('#editModel').modal('show');
            });
            //单项删除按钮事件
            $("#userTable").on("click","button[name='delete']",function (e) {
                let list=[];
                list.push($(this).data("username"));
                deleteUser(list);
            });
            //密码重置按钮
            $("#userTable").on("click","button[name='resetPass']",function (e) {
                let username= $(this).data("username");
                swal({
                        title: "确定重置密码?",
                        text: "",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "reset",
                        closeOnConfirm: false,
                        showLoaderOnConfirm: true
                    },
                    function () {
                        $.ajax({
                            url: rootPath + "/user/password/reset",
                            type: 'get',
                            data: {username:username},
                            success: function (data) {
                                if (data.code === '200') {
                                    swal("密码重置成功", "", "success");
                                } else {
                                    swal("密码重置失败", data.msg, "error");
                                }
                            }
                        });
                    });
            });
            //批量删除按钮事件
            $("#deleteUsers").click(function () {
                let list=$userTable.bootstrapTable("getSelections").map(function (m) {
                    return m.username;
                });
                deleteUser(list);
            });
            //编辑确认按钮
            $("#editUserDo").click(function () {
                let params={};
                params.username=$('#editUserName').val();
                params.realName=$('#editRealName').val();
                params.email=$("#editEmail").val();
                params.updateRoles=$.fn.zTree.getZTreeObj(editTreeId).getChangeCheckedNodes().filter(function (data) {
                    return data.parentTId;
                }).map(function (data) {
                    return {
                        id:data.id,
                        checked:data.checked
                    };
                });
                $.IOQuery({
                    url:rootPath+"/user/update",
                    type:"post",
                    contentType:"application/json; charset=utf-8",
                    data:JSON.stringify(params),
                    success:function (data) {
                        if (data.code==='200'){
                            $userTable.bootstrapTable('refresh');
                            swal("更新用户成功","","success");
                        }else{
                            swal("更新用户失败",data.msg,"error");
                        }
                    }
                });
            });
            //新增角色的事件
            $("#addUser").click(function () {
                loadRole(null,addTreeId);
                $('#addModel').modal('show');
            });
            //执行新增角色的事件
            $("#addUserDo").click(function () {
                var params= {};
                params.needRoles=$.fn.zTree.getZTreeObj(addTreeId).getChangeCheckedNodes().filter(function (data) {
                    return data.parentTId;
                }).map(function (data) {
                    return data.id;
                });
                params.userName=$("#addUserName").val();
                params.realName=$("#addRealName").val();
                params.email=$("#addEmail").val();
                $.IOQuery({
                    url:rootPath+'/user/add',
                    type:'post',
                    data:JSON.stringify(params),
                    contentType:"application/json; charset=utf-8",
                    success:function (data) {
                        if(data.code==='200'){
                            $userTable.bootstrapTable("refresh");
                            $("#addUserName").val('');
                            $("#addRealName").val('');
                            $("#addEmail").val('');
                            $('#addModel').modal('hide');
                            swal("新建用户成功","","success");
                        }
                        else
                            swal("新建用户失败",data.msg,"error");
                    }
                })
            });

            function loadRole(username,target) {
                $.ajax ({
                    url:rootPath+"/user/role/get",
                    type:'get',
                    data:{username:username},
                    success:function (data) {
                        let zTreeObj;
                        // zTree 的参数配置，深入使用请参考 API 文档（setting 配置详解）
                        // zTree 的数据属性，深入使用请参考 API 文档（zTreeNode 节点数据详解）
                        zTreeObj = $.fn.zTree.init($("#"+target), setting, data);
                        $.fn.zTree.getZTreeObj(target).expandAll(true);
                    }
                })
            }

            function deleteUser(list) {
                if (list.length>0) {
                    swal({
                            title: "确定删除用户?",
                            text: "",
                            type: "warning",
                            showCancelButton: true,
                            confirmButtonColor: "#DD6B55",
                            confirmButtonText: "delete",
                            closeOnConfirm: false,
                            showLoaderOnConfirm: true
                        },
                        function () {
                            $.ajax({
                                url: rootPath + "/user/delete",
                                type: 'post',
                                data: JSON.stringify(list),
                                contentType: "application/json; charset=utf-8",
                                success: function (data) {
                                    if (data.code === '200') {
                                        $userTable.bootstrapTable('refresh');
                                        swal("删除用户成功", "", "success");
                                    } else {
                                        swal("删除用户失败", data.msg, "error");
                                    }
                                }
                            });
                        });
                }else{
                    swal("请选择至少一个用户","","error");
                }
            }
        })
    </script>
</#macro>
